package com.glink.manage.mqtt;

import com.glink.manage.common.SpringContextUtil;
import com.glink.manage.mqtt.service.MessageResultService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : qiushaoshan
 * @create 2024/7/30 16:16
 */
@Slf4j
@Service
public class AIMqttCallback implements MqttCallback {
    
    @Autowired
    private MqttService mqttService;
    
    //连接丢失时触发（不包括主动disconnect）
    @Override
    public void connectionLost(Throwable throwable) {
        log.info("连接失败，请重新连接");

        try {
            // 30秒后重试
            Thread.sleep(30 * 1000L);
            
            // mqtt重试
            mqttService.checkRecreateClient();
        } catch (InterruptedException e) {
            log.error("mqtt连接失败，重试失败");
        }
       
    }
    
    //接收到内容触发
    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        log.info("MQTT：接收到的主题为：" + s);
        String result = new String(mqttMessage.getPayload(), StandardCharsets.UTF_8);
        log.info("MQTT：内容为：" + result);
        MessageResultService messageResultService = (MessageResultService) SpringContextUtil.getBean(MessageResultService.class);
        messageResultService.messageHandler(s, result);
    }
    
    //发布完消息触发
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("发布消息成功");
    }
}
